using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Web.SessionState;
using NetWing.Model;
using NetWing.Bll;
using Omu.ValueInjecter;
using NetWing.BPM.Core;
using NetWing.BPM.Core.Bll;
using NetWing.Common;
using NetWing.Common.Data;
using NetWing.Common.Data.SqlServer;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Excel;
using NetWing.Common.IO;
using NetWing.Common.IO.DirFile;
using NetWing.Common.Data.Filter;

namespace NetWing.BPM.Admin.MJUser.ashx
{
    /// <summary>
    ///  的摘要说明
    /// </summary>
    public class MJUserHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            int k;
            var json = HttpContext.Current.Request["json"];
            var rpm = new RequestParamModel<MJUserModel>(context) { CurrentContext = context };
            if (!string.IsNullOrEmpty(json))
            {
                rpm = JSONhelper.ConvertToObject<RequestParamModel<MJUserModel>>(json);
                rpm.CurrentContext = context;
            }

            switch (rpm.Action)
            {
                case "add":
                    MJUserModel a = new MJUserModel();
                    a.InjectFrom(rpm.Entity);
                    a.depid = SysVisitor.Instance.UserDepId;
                    a.ownner = SysVisitor.Instance.UserId;
                    context.Response.Write(MJUserBll.Instance.Add(a));
                    break;
                case "edit":
                    //编辑时不改变用户组所有者。要不然乱得一塌糊涂
                    MJUserModel d = new MJUserModel();
                    //d.InjectFrom(rpm.Entity);
                    //d.KeyId = rpm.KeyId;
                    //d.ownner = SysVisitor.Instance.UserId;//数据所有者ID
                    //d.depid = SysVisitor.Instance.UserDepId;//数据所有组ID
                    //context.Response.Write(MJUserBll.Instance.Update(d));
                    d.InjectFrom(rpm.Entity);
                    d.KeyId = rpm.KeyId;
                    context.Response.Write(MJUserBll.Instance.Update(d));
                    break;
                case "export":
                    //string fields = rpm.fields;
                    string fields = rpm.CurrentContext.Request["fields"];
                    string tablename = TableConvention.Resolve(typeof(MJUserModel));//得到表名
                    DataTable xlsDt = SqlEasy.ExecuteDataTable("select " + fields + " from " + tablename + "");
                    ExcelHelper.NPIOtoExcel(xlsDt, HttpContext.Current.Server.MapPath("\\upload\\excel\\" + tablename + ".xls"));
                    context.Response.Write("{\"status\":\"ok\",\"filename\":\"" + tablename + ".xls\"}");
                    break;
                case "inport"://从Excel导入到数据库
                    if (context.Request["REQUEST_METHOD"] == "OPTIONS")
                    {
                        context.Response.End();
                    }
                    SaveFile("~/temp/", context);
                    break;
                case "delete":
                    context.Response.Write(MJUserBll.Instance.Delete(rpm.KeyId));
                    break;
                case "alldel"://2017-04-05新增的功能 批量删除删除结果返回删除条数
                    context.Response.Write(NetWing.Dal.MJUserDal.Instance.Delete(rpm.KeyIds));
                    break;
                default:
                    //2017-6-1新增数据权限筛选
                    //新建一个筛选
                    //var str = new SqlFilter(GroupOp.AND.ToString(), new FilterRule("KeyId",21, "eq"));
                    //把筛选翻译成sql语句
                    //string sqlwhere = FilterTranslator.ToSql(str.ToString());
                    //数据权限筛选语句

                    string sqlwhere = "(depid in (" + SysVisitor.Instance.cookiesDepartments + "))";
                    if (SysVisitor.Instance.cookiesIsAdmin == "True")
                    { //判断是否是超管如果是超管理，所有显示
                        sqlwhere = " 1=1 ";//如果是超管则不显示
                    }
                    if (!string.IsNullOrEmpty(rpm.Filter))//如果筛选不为空
                    {
                        string str=" and "+ FilterTranslator.ToSql(rpm.Filter);
                        sqlwhere = sqlwhere +str;
                    }
                    //TableConvention.Resolve(typeof(MJUserModel)) 转换成表名
                    //默认排序keyid
                    string mysort = null;
                    if (rpm.Sort==null)
                    {
                        mysort = "keyid desc";
                    }
                    else
                    {
                        mysort = rpm.Sort;
                    }

                    var pcp = new ProcCustomPage(TableConvention.Resolve(typeof(MJUserModel)))
                    {
                        PageIndex = rpm.Pageindex,
                        PageSize = rpm.Pagesize,
                        OrderFields = mysort,
                        WhereString = sqlwhere
                    };
                    int recordCount;
                    DataTable dt = DbUtils.GetPageWithSp(pcp, out recordCount);
                    context.Response.Write(JSONhelper.FormatJSONForEasyuiDataGrid(recordCount, dt));
                    //旧的方法
                    //context.Response.Write(MJUserBll.Instance.GetJson(rpm.Pageindex, rpm.Pagesize, rpm.Filter, rpm.Sort, rpm.Order));
                    break;
            }
        }

        /// <summary>
        /// 文件保存操作
        /// </summary>
        /// <param name="basePath"></param>
        private void SaveFile(string basePath, HttpContext context)
        {
            var name = string.Empty;
            basePath = (basePath.IndexOf("~") > -1) ? context.Server.MapPath(basePath) :
            basePath;
            HttpFileCollection files = context.Request.Files;

            if (!Directory.Exists(basePath))//如果文件夹不存在创建文件夹
                Directory.CreateDirectory(basePath);
            //清空temp文件夹
            DirFileHelper.ClearDirectory(basePath);

            var suffix = files[0].ContentType.Split('/');
            var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1];
            var _temp = System.Web.HttpContext.Current.Request["name"];

            if (!string.IsNullOrEmpty(_temp))
            {
                name = _temp;
            }
            else
            {
                Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                name = rand.Next() + "." + _suffix;
            }

            var full = basePath + name;
            files[0].SaveAs(full);

            DataTable dt = NPOIHelper.ImportExceltoDt(full);
            string connectionString = SqlEasy.connString;
            SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            sqlbulkcopy.DestinationTableName = TableConvention.Resolve(typeof(MJUserModel));//数据库中的表名
                                                                                            //自定义的datatable和数据库的字段进行对应  
                                                                                            //sqlBC.ColumnMappings.Add("id", "tel");  
                                                                                            //sqlBC.ColumnMappings.Add("name", "neirong");  
            int k = dt.Rows.Count - 1;                                                                       //注意一个问题，最后一列是字段数
            for (int i = 0; i < (dt.Columns.Count - 1); i++)
            {
                sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName.ToString(), dt.Columns[i].ColumnName.ToString());

            }
            var _result = "";
            try
            {
                sqlbulkcopy.WriteToServer(dt);
                _result = "{\"msg\" : \"导入数据库成功!\", \"result\" : " + k + ", \"filename\" : \"" + name + "\"}";
            }
            catch (Exception)
            {
                _result = "{\"msg\" : \"导入失败,可能模板不对，或其他原因，建议导出数据作为模板重新处理。注意导入没有校验数据重复功能。请人工校验数据!\", \"result\" : 0, \"filename\" : \"" + name + "\"}";
                //throw;
            }



            System.Web.HttpContext.Current.Response.Write(_result);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}